import { defineComponent, reactive, ref } from "vue";
import Popup from "@/components/Popup/Popup";
import styles from "./Add.module.less";
import to from "await-to-js";
import _ from "lodash";
import { message } from "ant-design-vue";
import { $systemMenuTreeSelect } from "@/apis/system/menu/menu";
import { $systemMenuRoleMenuTreeselect } from "@/apis/system/menu/menu";
export default defineComponent({
  props: {
    service: {
      type: Object,
    }
  },
  emits: ["change"],
  setup(props, { emit, expose }) {
    const addPopupRef = ref(null as any);
    const formRef = ref(null as any);
    const state = reactive({
      type: "add",
      form: {
        roleId: null,
        roleName: null,
        roleKey: null,
        roleSort: null,
        status: "0",
        menuCheckStrictly: false,
        remark: null,
      },
      options: {
        menus: [] as any[],
      },
      menu_ids: [],
      menu_ids_half: [],
    })
    const editing = ref(false);
    const treeCheck = (checkedKeys: any, e: any) => {
      state.menu_ids_half = e.halfCheckedKeys || [];
    }
    // 获取分类
    const getMenus = async () => {
      const [err, res]: any = await to($systemMenuTreeSelect());
      if (!err) {
        state.options.menus = res?.data?.data || [];
      }
    }
    // 获取详情
    const getDetail = async () => {
      const [err, res]: any = await to(props.service?.detail(state.form.roleId));
      if (!err) {
        const resultObj = res?.data?.data;
        state.form.roleName = resultObj.roleName || null;
        state.form.roleKey = resultObj.roleKey || null;
        state.form.roleSort = resultObj.roleSort || null;
        state.form.status = resultObj.status || "0";
        state.form.remark = resultObj.remark || null;
      }
    }
    // 获取菜单项
    const findMenuItem = (menus, id) => {
      for (const node of menus) {
        if (node.id === id) {
            return node; // 找到目标节点，直接返回
        }
        if (node.children && node.children.length > 0) {
            const foundNode = findMenuItem(node.children, id); // 递归查找子节点
            if (foundNode) {
                return foundNode; // 在子节点中找到目标节点，返回
            }
        }
    }
    return null; // 遍历完整个树形结构仍未找到，返回null
    }
    // 获取用户菜单选择
    const getRoleMenus = async () => {
      const [err, res]: any = await to($systemMenuRoleMenuTreeselect(state.form.roleId || 0));
      if (!err) {
        let menus = res?.data?.menus || [];
        let menu_ids = res.data?.checkedKeys || [];
        state.menu_ids = menu_ids.filter((x: any) => !findMenuItem(menus, x).children || findMenuItem(menus, x).children?.length === 0) || [];
        state.menu_ids_half = menu_ids.filter((x: any) => findMenuItem(menus, x).children?.length > 0) || [];
      }
    }
    // 打开弹窗
    const open = async ({ type, roleId }) => {
      state.type = type;
      state.form.roleId = roleId;
      await getMenus();
      if (type === 'edit') {
        await getDetail();
        await getRoleMenus();
      }
      addPopupRef.value.open();
    }
    const submit = async () => {
      formRef.value
        .validate()
        .then(async () => {
          editing.value = true;
          const params = _.cloneDeep(state.form);
          params.menuIds = state.menu_ids?.length > 0 ? state.menu_ids.concat(state.menu_ids_half) : [];
          const [err, res]: any = await to((state.type === 'edit' ? props.service?.edit : props.service?.add)(params));
          if (!err) {
            message.success(state.type === 'edit' ? '编辑成功' : '添加成功');
            addPopupRef.value.close();
            emit('change');
          }
          editing.value = false;
        })
    }
    expose({
      open,
    })
    return () => (
      <Popup ref={addPopupRef}
        title={state.type === 'edit' ? "编辑角色" : "添加角色"}
        width="800px"
        oriState={state}
        v-slots={{
          footer: () => <>
            <a-button type="primary" loading={editing.value} onClick={() => { submit() }}>确定</a-button>
            <a-button onClick={() => { addPopupRef.value.close() }}>取消</a-button>
          </>
        }}
      >
        <div class={styles.container}>
          <div class={styles.formBox}>
            <a-form style={{ width: "100%" }} ref={formRef} model={state.form} label-col={{ style: { width: '130px', marginRight: '10px' } }} wrapper-col={{ span: 28 }}>
              <a-form-item required label="角色名称" name="roleName">
                <a-input v-model:value={state.form.roleName} placeholder="请输入角色名称" />
              </a-form-item>
              <a-form-item required label="权限字符" name="roleKey">
                <a-input v-model:value={state.form.roleKey} placeholder="请输入权限字符" />
              </a-form-item>
              <a-form-item required label="角色顺序" name="roleSort">
                <a-input-number style={{ width: "200px" }} min={0} v-model:value={state.form.roleSort} placeholder="角色顺序" />
              </a-form-item>
              <a-form-item label="状态" name="status">
                <a-radio-group
                  v-model:value={state.form.status}
                  name="radioGroup"
                >
                  <a-radio value={"0"}>正常</a-radio>
                  <a-radio value={"1"}>停用</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="菜单权限" name="menuIds">
                <div class={styles.treeArea}>
                  <a-tree
                    v-model={[state.menu_ids, 'checkedKeys']}
                    checkable
                    selectable={false}
                    fieldNames={{ children: "children", title: 'label', key: 'id' }}
                    tree-data={state.options.menus}
                    onCheck={treeCheck}
                  >
                  </a-tree>
                </div>
              </a-form-item>
              <a-form-item label="备注" name="remark">
                <a-textarea v-model:value={state.form.remark} />
              </a-form-item>
            </a-form>
          </div>
        </div>
      </Popup>
    )
  }
})